package ahblue.cn.tanzi.ui.circle;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.shehuan.nicedialog.BaseNiceDialog;
import com.shehuan.nicedialog.NiceDialog;
import com.shehuan.nicedialog.ViewConvertListener;
import com.shehuan.nicedialog.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.common.Config;
import ahblue.cn.tanzi.data.Result;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.jmessage.im.util.DialogCreator;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.ui.base.BaseActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IssueDynamicImageActivity extends BaseActivity {

    public static final int REQUEST_CODE_MAIN = 10; //请求码

    @BindView(R.id.gridView)
    GridView mGridView;
    @BindView(R.id.et_issue_dynamic)
    EditText mEditTextDynamic;
    @BindView(R.id.tv_issue_tongbu)
    TextView tvIssueTongbu;

    @BindView(R.id.cb_issue_dynamic)
    CheckBox mCheckBoxIsOnlyFriends;

    private ArrayList<String> mPicList = new ArrayList<>();
    private GridViewAdapter mGridViewAddImgAdapter; // 展示上传的图片的适配器

    private Dialog mDialogLoading;
    private String selectedCircleIds = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_issue_dynamic_image);

        ButterKnife.bind(this);

        initData();
        initView();
    }

    private void initData() {
    }

    private void initView() {
        mGridViewAddImgAdapter = new GridViewAdapter(this, mPicList);
        mGridView.setAdapter(mGridViewAddImgAdapter);
        mGridView.setOnItemClickListener(mGridViewItemClickListener);
    }

    @Override
    public void onBackPressed() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_cancel_confrim)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    protected void convertView(ViewHolder viewHolder, BaseNiceDialog dialog) {
                        TextView textViewMessage = viewHolder.getView(R.id.textViewMessage);
                        textViewMessage.setText("是否退出编辑？");

                        viewHolder.setOnClickListener(R.id.textViewConfirm, view -> {
                            setResult(RESULT_OK);
                            IssueDynamicImageActivity.super.onBackPressed();
                            dialog.dismiss();
                        });
                        viewHolder.setOnClickListener(R.id.textViewCancel, view -> {
                            dialog.dismiss();
                        });
                    }
                })
                .setMargin(50)
                .show(getSupportFragmentManager());
    }

    @OnClick(R.id.imageButtonLeft)
    void onClickImageButtonLeft() {
        onBackPressed();
    }

    @OnClick(R.id.tv_issue_tongbu)
    void onClickTvIssueTongbu(){
        Intent intent = new Intent(this, IssueDynamicChooseMyCircleActivity.class);
        startActivityForResult(intent,REQUEST_CODE_MAIN);
    }

    // 发表
    @OnClick(R.id.textViewRight)
    void onClickTextViewRight() {
        String strDynamic = mEditTextDynamic.getText().toString();
        if (strDynamic.length() == 0) {
            Toast.makeText(this, "内容不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        if (selectedCircleIds == null || "".equals(selectedCircleIds)){
            Toast.makeText(this, "请选择需要同步到的圈子", Toast.LENGTH_LONG).show();
            return;
        }

        mDialogLoading = DialogCreator.createLoadingDialog(this, "正在上传");
        mDialogLoading.show();

        int isFriends = mCheckBoxIsOnlyFriends.isChecked() ? 1 : 0;

        LoginResultModel model = LoginResultModel.getUserModel(this, LoginResultModel.class);
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.addBigShotCircleSendDynamic(model.token, strDynamic,selectedCircleIds, isFriends, mPicList,
                null, mCallbackAddDynamic);
    }

    private ApiCallback<Result> mCallbackAddDynamic = new ApiCallback<Result>() {
        @Override
        public void onSuccess(Result data) {
            Toast.makeText(IssueDynamicImageActivity.this, "发表成功", Toast.LENGTH_LONG).show();
            IssueDynamicImageActivity.this.setResult(RESULT_OK);
            IssueDynamicImageActivity.this.finish();

            if (mDialogLoading != null) {
                mDialogLoading.dismiss();
            }
        }

        @Override
        public void onFailed(String errorMsg) {
            if (mDialogLoading != null) {
                mDialogLoading.dismiss();
            }
        }
    };



    private AdapterView.OnItemClickListener mGridViewItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (i == adapterView.getChildCount() - 1) {
                // 如果“增加按钮形状的”图片的位置是最后一张，且添加了的图片的数量不超过9张，才能点击
                if (mPicList.size() == Config.MAX_SELECT_PIC_NUM) {
                    // 最多添加9张图片
                    viewPluImg(i);
                } else {
                    //添加凭证图片
                    selectPic(Config.MAX_SELECT_PIC_NUM - mPicList.size());
                }
            } else {
                viewPluImg(i);
            }
        }
    };

    /**
     * 查看大图
     * @param position 图片位置
     */
    private void viewPluImg(int position) {
        Intent intent = new Intent(this, PlusImageActivity.class);
        intent.putStringArrayListExtra(PlusImageActivity.ARG_IMG_LIST, mPicList);
        intent.putExtra(PlusImageActivity.ARG_POSITION, position);
        startActivityForResult(intent, REQUEST_CODE_MAIN);
    }

    /**
     * 打开相册或者照相机选择凭证图片，最多5张
     *
     * @param maxTotal 最多选择的图片的数量
     */
    private void selectPic(int maxTotal) {
        PictureSelectorConfig.initMultiConfig(this, maxTotal);
    }

    // 处理选择的照片的地址
    private void refreshAdapter(List<LocalMedia> picList) {
        for (LocalMedia localMedia : picList) {
            String mediaPath;
            // 被压缩后的图片路径
            if (localMedia.isCompressed()) {
                mediaPath = localMedia.getCompressPath(); // 压缩后的图片路径
            } else {
                mediaPath = localMedia.getPath();
            }
            mPicList.add(mediaPath); // 把图片添加到将要上传的图片数组中
        }

        mGridViewAddImgAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    refreshAdapter(PictureSelector.obtainMultipleResult(data));
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        }
        if (requestCode == REQUEST_CODE_MAIN && resultCode == PlusImageActivity.RESULT_CODE_VIEW_IMG && data != null) {
            //查看大图页面删除了图片
            ArrayList<String> toDeletePicList = data.getStringArrayListExtra(PlusImageActivity.ARG_IMG_LIST); //要删除的图片的集合
            mPicList.clear();
            mPicList.addAll(toDeletePicList);
            mGridViewAddImgAdapter.notifyDataSetChanged();
        }

        if (requestCode == REQUEST_CODE_MAIN && data != null){
            String ids = data.getStringExtra("selectedCircleIds");
            if (ids != null && !"".equals(ids)){
                selectedCircleIds = ids;
            }

            String selectedCircleNames = data.getStringExtra("selectedCircleNames");
            if (selectedCircleNames != null && !"".equals(selectedCircleNames)){
                selectedCircleNames = selectedCircleNames.substring(1);
                tvIssueTongbu.setText(selectedCircleNames);
            }

        }
    }



    class GridViewAdapter extends BaseAdapter {

        private Context mContext;
        private List<String> mList;
        private LayoutInflater inflater;

        GridViewAdapter(Context mContext, List<String> mList) {
            this.mContext = mContext;
            this.mList = mList;
            inflater = LayoutInflater.from(mContext);
        }

        @Override
        public int getCount() {
            int count = mList == null ? 1 : mList.size() + 1;
            if (count > Config.MAX_SELECT_PIC_NUM) {
                return mList.size();
            } else {
                return count;
            }
        }

        @Override
        public Object getItem(int i) {
            return mList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.item_select_image, parent,false);
            ImageView iv = (ImageView) convertView.findViewById(R.id.imageView);

            if (position < mList.size()) {
                // 代表+号之前的需要正常显示图片
                String picUrl = mList.get(position); // 图片路径
                Glide.with(mContext).load(picUrl).into(iv);
            } else {
                iv.setImageResource(R.drawable.btn_add);//最后一个显示加号图片
            }

            return convertView;
        }
    }
}
